/*
 * @Author: asushiye
 * @Date: 2020-07-02 15:30:23
 * @Commit: file content
 */
import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { AfMessageService } from '@core';
import { STColumn, STComponent } from '@delon/abc/st';
import { XlsxService } from '@delon/abc/xlsx';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { NzModalService } from 'ng-zorro-antd/modal';
import { format } from 'sql-formatter';

import { CgExcelService } from './cg-excel.service';
import { CodeGenService } from '../codegen.service';
import { CgUploadComponent } from '../core/upload/cg-upload.component';

@Component({
  selector: 'app-cg-excel',
  templateUrl: './cg-excel.component.html'
})
export class CgExcelComponent implements OnInit {
  rows: any[] = [];
  databaseTypes: any[] = [];
  currentDbType = 'mysql';
  currentDbSource = '';
  currentRecord: any;
  databaseSources: { [place: string]: string[] } = {
    mysql: ['mysql1', 'mysql2', 'mysql3'],
    postgresql: ['postgresql1', 'postgresql2']
  };
  queryParams: any = { fileName: '' };
  isLoading = false;
  scripts: any[] = [];

  @ViewChild('st', { static: false }) st!: STComponent;
  columns: STColumn[] = [
    { title: '编号', index: 'id', sort: true },
    { title: '文件名称', index: 'fileName' },
    { title: '扩展内容', index: 'extendedFields' },
    // { title: '创建时间', type: 'date', index: 'createdDate' },
    // { title: '更新人', index: 'lastModifiedBy' },
    // { title: '更新时间', type: 'date', index: 'lastModifiedDate' },
    {
      title: '状态',
      type: 'badge',
      index: 'syncCode',
      badge: {
        9: { text: '待处理', color: 'processing' },
        0: { text: '成功', color: 'success' },
        1: { text: '失败', color: 'error' }
      }
    },
    {
      title: '操作',
      buttons: [
        {
          text: '生成脚本',
          icon: 'create',
          tooltip: `生成脚本`,
          click: _record => {
            this.genScript(_record);
          }
        },
        {
          text: '下载源文件',
          icon: 'download',
          tooltip: `下载原始文件`,
          click: (record, _modal) => {
            this.downloadFile(record);
          }
        },
        { text: '脚本日志', icon: 'eye', click: (item: any) => this.viewLog(item) },
        // {
        //   text: '创建表结构',
        //   icon: 'edit',
        //   tooltip: `创建表结构`,
        //   click: (_record) => {
        //     this.genDb();
        //   },
        // },
        {
          text: '生成JPA代码',
          icon: 'file-zip',
          tooltip: `按此记录生成JPA代码`,
          click: _record => {
            this.downloadJpaZip(_record);
          }
        },
        {
          text: '更多',
          children: [
            {
              text: '归档',
              icon: 'delete',
              type: 'del',
              tooltip: `归档此记录`,
              pop: {
                title: '您确定要归档此记录吗？',
                okType: 'danger',
                icon: 'star'
              },
              click: (record, _modal) => {
                this.archive(record);
              }
            },
            {
              text: '查看JSON',
              icon: 'bug',
              click: (record, _modal) => {
                this.viewJson(record);
              }
            }
          ]
        }
      ]
    }
  ];

  constructor(
    private cdr: ChangeDetectorRef,
    private msg: AfMessageService,
    public cgExcelService: CgExcelService,
    private codegen: CodeGenService,
    private modal: ModalHelper,
    private router: Router,
    private modalForm: NzModalService,
    private xlsxService: XlsxService
  ) {}
  ngOnInit() {
    this.queryDatabaseType();
    this.queryDataSource();
    this.query();
  }

  public queryDataSource() {
    this.isLoading = true;
    this.cdr.detectChanges();
    try {
      this.codegen.getDataSource().subscribe(body => {
        if (body.status) {
          this.databaseSources = {};
          this.databaseSources = body.data;
          if (this.databaseSources['mysql'] != undefined && this.databaseSources['mysql'].length >= 1) {
            this.currentDbSource = this.databaseSources['mysql'][0];
          }
          console.log(JSON.stringify(this.databaseSources));
        } else {
          this.msg.notice_warning('查询数据源', `警告编号${body.code};  警告信息${body.msg}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.isLoading = false;
        this.cdr.detectChanges();
      }, 200);
    }
  }

  public queryDatabaseType() {
    this.isLoading = true;
    this.cdr.detectChanges();
    try {
      this.codegen.getDataTypeList().subscribe(body => {
        if (body.status) {
          this.databaseTypes = [];
          this.databaseTypes = body.data;
          console.log(JSON.stringify(this.databaseTypes));
        } else {
          this.msg.notice_warning('查询数据库类型列表', `警告编号${body.code};  警告信息${body.msg}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.isLoading = false;
        this.cdr.detectChanges();
      }, 200);
    }
  }

  public query() {
    this.isLoading = true;
    this.cdr.detectChanges();
    try {
      this.cgExcelService.query(this.queryParams.fileName).subscribe(body => {
        console.log(body);
        if (body.status) {
          this.rows = [];
          this.rows = body.data;
        } else {
          this.msg.notice_warning('查询文件', `警告信息: ${body.msg} ; ${body.data}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.isLoading = false;
        this.cdr.detectChanges();
      }, 200);
    }
  }

  downloadJpaZip(record: any = {}) {
    this.cdr.detectChanges();
    try {
      const url = this.cgExcelService.downloadJpaZip(record.id, false);
      window.open(url);
    } finally {
      this.cdr.detectChanges();
    }
  }

  executeScript() {
    try {
      this.cgExcelService.executeScript(this.currentRecord.id, this.currentDbType, this.currentDbSource, false).subscribe(body => {
        if (body.status) {
          this.msg.notice_success('表结构创建成功', ``);
          this.query();
          // record.sysStatus = body.status;
          // record.syncCode = body.code;
          // record.syncMsg = body.msg;
        } else {
          this.msg.notice_warning('表结构创建失败', `警告信息: ${body.msg} ; ${body.data}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
      }, 200);
    }
  }

  archive(item: any) {
    try {
      this.cgExcelService.archive(item.id).subscribe(body => {
        if (body.status) {
          this.rows = [];
          this.msg.notice_success('归档记录', `${item.fileName} 记录归档成功`);
          this.query();
        } else {
          this.msg.notice_warning('归档记录', `警告信息: ${body.msg} ; ${body.data}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
      }, 200);
    }
  }

  upload(record: any = {}) {
    record.business = this.cgExcelService.fileType;
    record.title = '表结构';
    this.modal.create(CgUploadComponent, { record }, { size: 'md' }).subscribe(res => {
      if (res === 'ok') {
        this.query();
      }
    });
  }

  viewLog(record: any = {}) {
    this.router.navigateByUrl(`/codegen/database/script/log?sourceId=${record.id}`);
  }

  viewLog2() {
    this.router.navigateByUrl(`/codegen/database/script/log?sourceId=${this.currentRecord.id}`);
  }

  // 下载源设计文件
  downloadFile(record: any = {}) {
    this.cdr.detectChanges();
    try {
      const url = this.cgExcelService.getDownloadFileUrl(record.id, false);
      window.open(url);
    } finally {
      this.cdr.detectChanges();
    }
  }

  // 下载模版文件
  downloadTemplate() {
    this.cdr.detectChanges();
    try {
      this.codegen.downloadTemplateFile(this.cgExcelService.fileType);
    } finally {
      this.cdr.detectChanges();
    }
  }

  // 查看当然记录 -- 用于开发测试
  viewJson(record: any = {}) {
    this.codegen.viewJson(record);
  }

  drawer_size: 'large' | 'default' = 'large';
  drawer_Title = 'demo';
  drawer_visible = false;

  scriptAll = '';

  genScript(record: any = {}) {
    this.currentRecord = record;
    this.drawer_Title = this.currentRecord.fileName;
    this.drawer_visible = true;
    this.generateScript();
  }

  generateScript() {
    try {
      this.cgExcelService.generateScript(this.currentRecord.id, this.currentDbType, false).subscribe(body => {
        this.scriptAll = '';
        if (body.status) {
          let table = '';
          // this.msg.notice_success('脚本生成成功', ``);
          // this.drawer_Title = this.currentRecord.fileName;
          this.scripts = body.data;
          this.currentDbType = body.msg;
          this.scripts.forEach(item => {
            if (table != item.tableName) {
              table = item.tableName;
              this.scriptAll = `${this.scriptAll}-- ${item.tableName}-${item.tableComment} \n`;
            }
            this.scriptAll = `${this.scriptAll + this.codegen.sqlformat(item.script, this.currentDbType)};\n`;
          });
          // this.drawer_visible = true;
        } else {
          // this.drawer_visible = false;
          this.msg.notice_warning('脚本生产失败', `警告信息: ${body.msg} ; ${body.data}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
      }, 200);
    }
  }

  drawer_close(): void {
    this.drawer_visible = false;
  }

  dbTypeChange(value: string): void {
    this.currentDbSource = this.databaseSources[value][0];
  }
}
